﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NetSurveillance.WebApp.DataServices.Models;
using NetSurveillance.WebApp.Foundations;
using NetSurveillance.WebApp.Utilities;

namespace NetSurveillance.WebApp.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class WebAppAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");
            if (filterContext.HttpContext.IsDebuggingEnabled &&
                PermissionHelper.ControllerDisplayName(filterContext.Controller.GetType()) == "Init")
                return;
            var currentUser = PersistentDataContainer.Current.Read<User>(PresetValues.SessionKeys.CurrentUser);
            if (currentUser == null || !filterContext.HttpContext.Request.IsAuthenticated)
                filterContext.Result = new HttpUnauthorizedResult();
            //var userMenus = PersistentDataContainer.Current.Read<IEnumerable<UserMenu>>(PresetValues.SessionKeys.UserMenu);
            //var actPmsList = PersistentDataContainer.CurrentCache.Read<IList<ActionPermission>>(PresetValues.SessionKeys.ActPermissions);
            //if(actPmsList == null || actPmsList.Count == 0) return;
            //string actionName = filterContext.ActionDescriptor.ActionName;
            //string ctlName = PermissionHelper.ControllerDisplayName(filterContext.Controller.GetType());
            //var actPms = actPmsList.FirstOrDefault(p => p.Action == actionName && p.Controller == ctlName);
            //if(actPms == null) return;
            //var menu =
            //    userMenus.FirstOrDefault(p => (p.Menu.RelativeUrl.Contains(actionName) || p.Menu.AbsoluteUrl.Contains(actionName)) &&
            //                                  (p.Menu.RelativeUrl.Contains(ctlName) || p.Menu.AbsoluteUrl.Contains(ctlName)));
            //if (menu == null || (actPms.Permission & menu.Permission) != actPms.Permission)
            //    filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}